package com.kx.center.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public class HttpClientUtil {

	// 发送post请求
	public static String post(String url, String data) throws HttpException,
			IOException {

		HttpClient httpclient = new HttpClient();
		PostMethod method = new PostMethod(url);

		method.addRequestHeader("appkey", "wizarpos6c78ddcakh49c936fc724");
		method.addRequestHeader("appsecret",
				"sM4AOVdWfPE4DxkXGEs8VFjJDFzC__AUN6pbDB03sGU-0vQYe3");

		StringRequestEntity requestEntity = new StringRequestEntity(data,
				"application/json", "UTF-8");
		method.setRequestEntity(requestEntity);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}

	// 发送get请求
	public static String sendGet(String url, String param) throws UnsupportedEncodingException {
		String result = "";
		result = URLEncoder.encode(result, "utf-8");
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	// 模拟put请求
	public static String doPut(String url, String params) throws Exception {
		HttpClient httpclient = new HttpClient();
		PutMethod method = new PutMethod(url);

		StringRequestEntity requestEntity = new StringRequestEntity(params,
				"application/x-www-form-urlencoded", "UTF-8");
		method.setRequestEntity(requestEntity);

		int code = httpclient.executeMethod(method);

		byte[] responseBody = null;

		if (code == HttpStatus.SC_OK) {
			Header contentEncoding = method
					.getResponseHeader("Content-Encoding");
			if (contentEncoding != null
					&& contentEncoding.getValue().toLowerCase().indexOf("gzip") > -1) {
				InputStream is = method.getResponseBodyAsStream();
				GZIPInputStream gzip = new GZIPInputStream(is);
				byte[] buf = new byte[1024];

				int num = -1;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();

				while ((num = gzip.read(buf, 0, buf.length)) != -1) {
					baos.write(buf, 0, num);
				}
				responseBody = baos.toByteArray();
				baos.flush();
				baos.close();
				gzip.close();
				is.close();
			} else {
				responseBody = method.getResponseBody();
			}

			Header contentType = method.getResponseHeader("Content-Type");
			if (contentType != null) {
				String encoding = contentType.getValue().toUpperCase();

				Pattern pattern = Pattern.compile("CHARSET=([^;]*)");
				Matcher matcher = pattern.matcher(encoding);
				String charset = matcher.find() ? matcher.group(1) : null;

				if (charset != null) {
					responseBody = (new String(responseBody, charset))
							.getBytes("UTF-8");
				}
			}
		}
		String result = new String(responseBody);
		return result;
	}

	/**
	 * 获取饿了么请求sig
	 */
	private static String concatParams(Map<String, String> params2)
			throws UnsupportedEncodingException {
		Object[] key_arr = params2.keySet().toArray();
		Arrays.sort(key_arr);
		String str = "";

		for (Object key : key_arr) {
			String val = params2.get(key);
			key = URLEncoder.encode(key.toString(), "UTF-8");
			val = URLEncoder.encode(val, "UTF-8");
			str += "&" + key + "=" + val;
		}

		return str.replaceFirst("&", "");
	}
	
	private static String byte2hex(byte[] b) {
		StringBuffer buf = new StringBuffer();
		int i;

		for (int offset = 0; offset < b.length; offset++) {
			i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}

		return buf.toString();
	}

	public static String genSig(String pathUrl, Map<String, String> params,
			String consumerSecret) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		String str = concatParams(params);
		str = pathUrl + "?" + str + consumerSecret;

		MessageDigest md = MessageDigest.getInstance("SHA1");
		return byte2hex(md.digest(byte2hex(str.getBytes("UTF-8")).getBytes()));
	}
	
	public static void main(String[] args) throws Exception,
			UnsupportedEncodingException {
		try {
			Integer timestamp = null;
			timestamp = (int) (System.currentTimeMillis() / 1000);
			Map<String, String> maps = new HashMap<String, String>();
			maps.put("consumer_key", "9066930640");
			maps.put("timestamp", timestamp.toString());
			String consumer_secret = "39b4e7076046cc81d39d92481fc16aea22ef1b43";
			String order_url = "http://v2.openapi.ele.me/order/100215191702093899/";
			String orderSig = HttpClientUtil.genSig(order_url, maps,
					consumer_secret);
			String order_params = "&consumer_key=9066930640&sig=" + orderSig
					+ "&timestamp=" + timestamp + "";
			String orderjson = HttpClientUtil.sendGet(order_url, order_params);
			System.out.println(orderjson);
//			String url = "http://ground.kxfresh.com:8080/api/trade/elmPush";
//			Map<String, String> maps = new HashMap<String, String>();
//			maps.put("consumer_key", "9066930640");
//			maps.put("eleme_order_ids", "100215191702093899");
//			maps.put("timestamp", "1449214990");
//			maps.put("push_action", "1");
//			String orderSig = HttpClientUtil.genSig(url, maps,consumer_secret);
//			System.out.println(orderSig);
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
